package org.porridge.util;

import java.io.File;
import java.sql.SQLException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

import org.db.createdao.BaseDao;
import org.db.createsql.RealizeDaoInter;
import org.porridge.module.fun.po.Fun;
import org.porridge.prdblog.article.po.Article;
import org.porridge.util.qiniu.QiniuUtil;
import org.transmit.ActionContext;
import org.transmit.ActionUtil;
import org.transmit.ThreadDao;
import org.transmit.util.FileUtil;

import jodd.mail.Email;
import jodd.mail.EmailAttachment;
import jodd.mail.EmailMessage;
import jodd.mail.Pop3Server;
import jodd.mail.Pop3SslServer;
import jodd.mail.ReceiveMailSession;
import jodd.mail.ReceivedEmail;
import jodd.mail.SendMailSession;
import jodd.mail.SmtpSslServer;

public class EmailUitl extends Thread{
	private int type=-1;//0发送邮件  1接收
	private String content;//发送邮件内容
	
	public EmailUitl(int type,String content){
		this.type=type;
		this.content=content;
	}
	
	
	public void run() {
		if(type==0 && content!=null){//错误发送邮件,多线程发送
			sendMail(Constant.SETTING.getSys_user()+" error message",content);
		}else if(type==1){
			addEmail();
		}
	}
	public void sendMail(String title,String contenxt_bak){
		Email email = Email.create()
		        .from(Constant.SETTING.getError_email())
		        .to(Constant.SETTING.getError_email())
		        .subject(title)
		        .addHtml(contenxt_bak,"UTF-8");
		SmtpSslServer ser=new SmtpSslServer(Constant.SETTING.getEmail_smtp(),Constant.SETTING.getEmail_user(),Constant.SETTING.getEmail_pas());
		SendMailSession session = ser.createSession();
	    session.open();
	    session.sendMail(email);
	    session.close();
	}
	/**
	 * 收取邮件.并且录入数据库
	 */
	private void addEmail(){
		RealizeDaoInter dao=ThreadDao.getDaoInter();
		Pop3Server popServer = new Pop3SslServer(Constant.SETTING.getEmail_smtp(),Constant.SETTING.getEmail_user(),Constant.SETTING.getEmail_pas());
	    ReceiveMailSession session = popServer.createSession();
	    session.open();
	    ReceivedEmail[] emails = session.receiveEmailAndMarkSeen();
	    if (emails != null) {
	        for (ReceivedEmail email : emails) {
	        	String title=email.getSubject();//邮件标题
	        	title=title!=null?title.trim():"";
	        	if(title.indexOf(Constant.SETTING.getSys_user())==0){
	        		title=title.replace(Constant.SETTING.getSys_user()+"#","");
	        		String type=title.substring(0,title.indexOf("#"));
	        		try {
						List<Fun> funs=dao.getList(Fun.class,"*","type='3' and ftltype='2' and name='"+type+"'");
						if(funs.size()!=0){
							title=title.substring(title.indexOf("#")+1,title.length());//取得标题
							Fun fun=funs.get(0);
							Article art=new Article();//开始组装文章
							art.setTitle(title);
							art.setType("1");
							art.setCls(fun.getFuncode());
							art.setSeo(title);
							art.setSendtime(BaseUtil.convertDate(email.getSentDate()));
							art.setLabletype("1");
							art.setAdduserid("email");
							art.setAddusername("邮件发文");
				            List<EmailMessage> messages = email.getAllMessages();
				            for (EmailMessage msg : messages) {
				                if("text/plain".equals(msg.getMimeType())){
				                	int maxlen=Integer.valueOf(Constant.SETTING.getPage_breviary());
				                	if(msg.getContent().length()>maxlen)
				                		art.setBreviary(msg.getContent().substring(0,maxlen)+"...");
				                	else
				                		art.setBreviary(msg.getContent());
				                }else if("text/html".equals(msg.getMimeType()))
				                	art.setAtr_content(msg.getContent());
				            }
				            String saveid=dao.save(art);//保存文章
				            
				            if(email.getPriority()!=0){//判断附件个数
					            List<EmailAttachment> attachments = email.getAttachments();
					            if (attachments != null) {
					            	String url="html/email_docu/"+BaseUtil.convertDate(new Date(),"yyyy-MM-dd")+"/"+saveid;
					            	File file=new File(FileUtil.URL.substring(0,FileUtil.URL.indexOf("WEB-INF"))+url);
					            	if(!file.exists())file.mkdirs();
					            	String projname=Constant.PROJECTPATH;
					            	
					            	String content=art.getAtr_content();
					            	Map<String,String> maps=null;//存放附件 key:名称,value:地址
					                for (EmailAttachment attachment : attachments) {
					                    attachment.writeToFile(new File(FileUtil.URL.substring(0,FileUtil.URL.indexOf("WEB-INF"))+url,attachment.getName()));
					                    if(attachment.getContentId()!=null){
					                    	if(QiniuUtil.uploadFile(Constant.SETTING.getQiniu_name(),Constant.SETTING.getQunui_first()+"/images/"+attachment.getName(),FileUtil.URL.substring(0,FileUtil.URL.indexOf("WEB-INF"))+url+"/"+attachment.getName()))//如果七牛上传成功则引入七牛的地址.否则还是用自己的
					                    		content=content.replaceAll("cid:"+attachment.getName(),"http://porridge.qiniudn.com/"+Constant.SETTING.getQunui_first()+"/images/"+attachment.getName());
					                    	else
					                    		content=content.replaceAll("cid:"+attachment.getName(),projname+"/"+url+"/"+attachment.getName());
					                    }else{
					                    	if(maps==null)maps=new HashMap<String, String>();
					                    	String uuid=BaseUtil.getUUID();
					                    	if(QiniuUtil.uploadFile(Constant.SETTING.getQiniu_name(),Constant.SETTING.getQunui_first()+"/document/"+uuid+"_"+attachment.getName(),FileUtil.URL.substring(0,FileUtil.URL.indexOf("WEB-INF"))+url+"/"+attachment.getName()))
					                    		maps.put(attachment.getName(),"http://porridge.qiniudn.com/"+Constant.SETTING.getQunui_first()+"/document/"+uuid+"_"+attachment.getName());
					                    	else
					                    		maps.put(attachment.getName(),projname+"/"+url+"/"+attachment.getName());
					                    }
					                }
					                if(maps!=null){//如果有附件则保存起来然后再修改一下.
					                	StringBuffer fj=new StringBuffer();
					                	fj.append("<br/><br/>文章附件:");
					                	 Set<Map.Entry<String, String>> lv=maps.entrySet();
					                	 for(Map.Entry<String, String> l:lv)
					                		 fj.append("&nbsp;&nbsp;&nbsp;<a target=\"_blank\" href=\""+l.getValue()+"\">"+l.getKey()+"</a>");
					                	  content+=fj;
					                	  art=new Article();
					                	  art.setId(saveid);
					                	  art.setAtr_content(content);
					                	  dao.update(art);
					                }
					            }
				            }
						}else{
							addEmailError(email.getSubject(),"未在找到归属标签");
						}
						dao.getConnection().commit();
					} catch (Exception e) {
						try {
							dao.getConnection().rollback();
						} catch (SQLException e1) {
							e1.printStackTrace();
						}
						e.printStackTrace();
					}
	        	}else{
	        		addEmailError(email.getSubject(),"接口暗号错误");
	        	}
	        }
	    }
	    session.close();
	}
	/**
	 * 收集错误邮件提示
	 */
	private void addEmailError(String title,String errortype){
		sendMail(Constant.SETTING.getSys_user()+" 收信错误","尊敬的管理员:<br/><br/>&nbsp;&nbsp;&nbsp;&nbsp;"
				+ "系统于"+BaseUtil.convertDate(new Date())+"尝试收取邮件("+title+")错误.原因:"+errortype+",请检查数据.谢谢.");
	}
}
